package com.xuhu.controller;

import javax.security.auth.login.LoginContext;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.xuhu.pojo.Reader;
import com.xuhu.service.impl.ReaderServiceImpl;

@Controller
@RequestMapping("/reader")
public class ReaderController {

	@Autowired
	private ReaderServiceImpl readerServiceImpl;
	@Autowired
	private Reader reader;
	@RequestMapping("/register")
	public String registerReader(@RequestParam("code")String code, @RequestParam("password")String pwd,HttpSession httpSession) {
		if(code == null || code == "" || pwd == null || pwd == "") {
			return "index";
		}else {
			String existCode = readerServiceImpl.getCode(code);
			if(existCode != null) {
				httpSession.setAttribute("msg", "该账号已存在，请重新注册新账号~");
				return "fail";
			}
			int row = readerServiceImpl.insertReadCode(code,pwd);
			if(row > 0) {
				httpSession.setAttribute("msg", "新增成功！");
				httpSession.setAttribute("code", code);
				httpSession.setAttribute("pwd", pwd);
				return "updateMessage";
			}
		}
		
		return "updateMessage";
	}
	@RequestMapping("/login")
	public String login() {
		return "login";
	}
	@RequestMapping("/logging")
	public String loginReader(@RequestParam("code")String code, @RequestParam("password")String pwd,HttpSession httpSession) {
		if(code == null || code == "") {
			return "index";
		}
		Reader realpwd = readerServiceImpl.getpwdbycode(code);
		if(realpwd != null && pwd.equals(realpwd.getPassword())) {
			httpSession.setAttribute("code", code);
			return "showreader";
		}
		httpSession.setAttribute("msg", "您输入的密码有误，请重新回到首页输入");
		return "fail";
	}
	@RequestMapping("/updateMessage")
	public String updateReaderMessage(@RequestParam("code")String code,@RequestParam("password")String password,@RequestParam("name")String name,
			@RequestParam("addres")String addres,@RequestParam("hobby")String hobby,HttpSession httpSession) {
		reader.setCode(code);
		reader.setPassword(password);
		reader.setName(name);
		reader.setAddres(addres);
		reader.setHobby(hobby);
		if(reader == null ) {
			return "index";
		}
		int row = readerServiceImpl.updateReaderMessage(reader);
		if(row > 0) {
			return "showreader";
		}
		httpSession.setAttribute("msg", "操作失败，请回到首页重新输入");
		return "fail";
	}
}
